package com.wells.slide.manager;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;

import org.apache.http.conn.ConnectTimeoutException;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.Context;
import android.util.Log;

public class FileManager
{
    private final String                   TAG              = FileManager.class.getSimpleName();
    private static FileManager             mInstance;
    private String                         mPhotoDir;

    private int                            TIME_OUT_SEC     = 10000;

    private FileInputStream                mFileInputStream = null;
    private URL                            connectUrl       = null;

    private String                         lineEnd          = "\r\n";
    private String                         twoHyphens       = "--";
    private String                         boundary         = "*****";
    
    public enum DownloadState
    {
        LOADING,
        FAILED,
        COMPLETE
    }

    public FileManager( Context context )
    {
        mPhotoDir = context.getCacheDir() + "/photo/";
        
        try
        {
            File dir = new  File( mPhotoDir );

            // ================================================================
            if( false == dir.exists() )
            {
                dir.mkdir();
            }
            // ================================================================
        }
        catch( Exception e )
        {
            Log.e( TAG, e.toString() );
        }
    }

    public static FileManager getInstance( Context context )
    {
        if ( mInstance == null )
        {
            mInstance = new FileManager( context );
        }

        return mInstance;
    }

  
    public String upload( String fileName,
                          String filePath,
                          String uploadPath )
    {
        String mResultData = "";
        try
        {
            mFileInputStream = new FileInputStream( filePath );
            connectUrl = new URL( uploadPath );

            HttpURLConnection conn = (HttpURLConnection)connectUrl.openConnection();
            conn.setDoInput( true );
            conn.setDoOutput( true );
            conn.setUseCaches( false );
            conn.setRequestMethod( "POST" );
            conn.setConnectTimeout( TIME_OUT_SEC );
            conn.setReadTimeout( TIME_OUT_SEC );

            conn.setRequestProperty( "Connection", "Keep-Alive" );
            conn.setRequestProperty( "Content-Type",
                                     "multipart/form-data;boundary=" + boundary );

            // write data
            DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
            
            dos.writeBytes( twoHyphens + boundary + lineEnd );
            dos.writeBytes( "Content-Disposition: form-data; name=\"" + "subject" + "\"" + lineEnd );
            dos.writeBytes( "test123");
            dos.writeBytes( lineEnd );

            dos.writeBytes( twoHyphens + boundary + lineEnd );
            dos.writeBytes( "Content-Disposition: form-data; name=\"" + "cate2" + "\"" + lineEnd );
            dos.writeBytes( "48");
            dos.writeBytes( lineEnd );
            
            dos.writeBytes( twoHyphens + boundary + lineEnd );
            dos.writeBytes( "Content-Disposition: form-data; name=\"img\";filename=\"" + fileName + "\"" + lineEnd );
            dos.writeBytes( lineEnd );

            int bytesAvailable = mFileInputStream.available();
            int maxBufferSize = 2048;
            int bufferSize = Math.min( bytesAvailable, maxBufferSize );

            byte[] buffer = new byte[bufferSize];
            int bytesRead = mFileInputStream.read( buffer, 0, bufferSize );

            while ( bytesRead > 0 )
            {
                dos.write( buffer, 0, bufferSize );
                bytesAvailable = mFileInputStream.available();
                bufferSize = Math.min( bytesAvailable, maxBufferSize );
                bytesRead = mFileInputStream.read( buffer, 0, bufferSize );
            }

            dos.writeBytes( lineEnd );
            dos.writeBytes( twoHyphens + boundary + twoHyphens + lineEnd );

            mFileInputStream.close();
            dos.flush();

            int ch;
            InputStream is = conn.getInputStream();
            StringBuffer b = new StringBuffer();
            while ( ( ch = is.read() ) != -1 )
            {
                b.append( (char)ch );
            }
            String s = b.toString();
            Log.v("moon","s      "+s);
//            mResultData = parseXML( s );
//            Log.v("moon","mResultData      "+mResultData);

            dos.close();

        }
        catch(UnknownHostException ue)
        {
            ue.printStackTrace();
            return "error";
        }
        catch (SocketTimeoutException e)
        {
            e.printStackTrace();
            return "error";
        }
        catch (ConnectTimeoutException e)
        {
            e.printStackTrace();
            return "error";
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return "error";
        }
        catch ( Exception e )
        {
            e.printStackTrace();
            return "error";
        }
        
        return mResultData;
    }
    
    
    public String parseXML( String xml )
    {
        boolean msg = false;
        String tag;
        String resultMsg = "";

        try
        {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = factory.newPullParser();
            parser.setInput( new StringReader( xml ) );

            int eventType = parser.getEventType();
            
            while ( eventType != XmlPullParser.END_DOCUMENT )
            {
                switch ( eventType )
                {
                    case XmlPullParser.TEXT:
                        
                        tag = parser.getName();

                        if ( msg )
                        {
                            resultMsg = parser.getText();
                        }
                        
                        break;
                        
                    case XmlPullParser.END_TAG:
                        
                        tag = parser.getName();
                        
                        if ( tag.compareTo( "msg" ) == 0 )
                        {
                            msg = false;
                        }
                        
                        break;
                        
                    case XmlPullParser.START_TAG:
                        
                        tag = parser.getName();
                        
                        if ( tag.compareTo( "msg" ) == 0 )
                        {
                            msg = true;
                        }
                        
                        break;
                }
                eventType = parser.next();
            }
        }
        catch ( Exception e )
        {
            return "error";
        }
        
        return resultMsg;
    }
}
